package com.rentong.utils;

import com.aliyun.oss.OSS;
import com.aliyun.oss.OSSClientBuilder;
import com.aliyun.oss.OSSException;
import com.aliyun.oss.common.auth.DefaultCredentialProvider;
import com.rentong.constants.WxConstant;

import java.io.InputStream;

public class OssUtil {
    private static final String yuMing = "https://chef2025.oss-cn-shanghai.aliyuncs.com/";

    // 创建 OSSClient 实例
    private static OSS createClient() {
        String endpoint = "oss-cn-shanghai.aliyuncs.com";
        String region = "cn-hangzhou";
        DefaultCredentialProvider credentialProvider = new DefaultCredentialProvider(WxConstant.accessKey, WxConstant.secretKey);
        OSS ossClient = OSSClientBuilder.create()
                .endpoint(endpoint)
                .credentialsProvider(credentialProvider)
                .build();
        return ossClient;
    }

    public static String upload(InputStream inputStream, String fileName) {
        OSS ossClient = createClient();
        String bucketName = "chef2025";
        try {
            // 1. 创建存储空间（Bucket）
            ossClient.createBucket(bucketName);
            // 2. 上传文件
            ossClient.putObject(bucketName, fileName, inputStream);
        } catch (OSSException oe) {
            System.out.println(oe.getMessage());
        } finally {
            ossClient.shutdown();
        }
        String url = yuMing + fileName;
        return url;
    }
}
